@echo off
echo ========================================
echo Redis Cluster Initialization Script
echo ========================================
echo.

rem   Enter one of the containers, for example redis-6001
rem   docker exec -it redis-6001 bash

rem   Execute cluster creation command inside the container
rem   redis-cli -a Redis@2024#Prod --cluster create 192.168.5.7:6001 192.168.5.7:6002 192.168.5.7:6003 192.168.5.7:6004 192.168.5.7:6005 192.168.5.7:6006 --cluster-replicas 1

rem Check if docker is available
where docker >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [ERROR] docker command not found, please ensure Docker is installed and running
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

:: Check if redis-6001 container is running
docker ps | findstr "redis-6001" >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [ERROR] redis-6001 container is not running, please start the containers first
    echo [INFO] Run: docker-compose up -d
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

echo Waiting for Redis nodes to start...
timeout /t 10 /nobreak >nul

echo.
echo Starting Redis cluster initialization...
echo.

docker exec redis-6001 redis-cli -a 123456 --cluster create ^
  redis-6001:6379 redis-6002:6379 redis-6003:6379 ^
  redis-6004:6379 redis-6005:6379 redis-6006:6379 ^
  --cluster-replicas 1 --cluster-yes

set CLUSTER_INIT_RESULT=%ERRORLEVEL%

echo.
echo ========================================
if %CLUSTER_INIT_RESULT% equ 0 (
    echo [SUCCESS] Redis cluster initialization completed!
) else (
    echo [WARNING] Cluster initialization may have completed or encountered an error, trying to continue...
)
echo ========================================
echo.

echo Checking cluster node information...
echo.
docker exec redis-6001 redis-cli -a 123456 cluster nodes

set NODES_CHECK_RESULT=%ERRORLEVEL%

echo.
echo ========================================
if %NODES_CHECK_RESULT% equ 0 (
    echo [SUCCESS] Cluster node status is normal
) else (
    echo [ERROR] Unable to retrieve cluster node information, please check Redis service status
)
echo ========================================

echo.
echo Press any key to exit...
pause >nul

exit /b %CLUSTER_INIT_RESULT%